$(function () {

    //初始化专业
    $.initSubject({
        element:'classes-subject-box',//初始化专业select元素的ID
        context:'classes-subject-context',//显示专业/科目名字内容ID
        initData:$('#subjectIds').val(),//初始化显示的专业数据，默认不设置
        removeCallback:function(parentId,subjectIds){//删除回调
            resetSubjectIds()
        },
        confirmCallback:function(parentId,subjectIds){//点击确认回调
            resetSubjectIds()
        }
    });
    /**
     * 重置专业ID串
     */
    function resetSubjectIds() {
        var _subjectIds = $.getAllSubjectIds("classes-subject-context");
        $("input[name=subjectIds]").val(_subjectIds);
    }

    $('body').on('ifChanged', 'input[name=classesType]', function () { // 课程班级 自由班级切换
        var free = isFreeClasses();
        if (free) {
            $('#classes-course tr[data-course]').remove();
        }
        $('#selectCourse').parents('div.form-group').toggleClass('hide', free).next().toggleClass('hide', free);
        $('#classes-course div.noDataTipsBox').parents('tr').toggleClass('hide', free);
        // 课程班级修改科目为单选
        $('#select2').attr('multiple', free).chosen('destroy').chosen();
    }).on('click', '#selectCourse', function () { // 选择课程
        selectCourse({
            selectType:"radio",
            type:1,
            callback:'selectCourseCallback'
        });
    }).on('click', '#select-image', function () { // 选择班级图标
        initUpdateFileWin({
            fileType: 'img',//文类类型["img","ico","xls","pdf","zip"]
            callback: 'uploadCallback',
            cut: true,//开启剪切
            imgSize: DEFAULT_CLASS_IMG_SIZE,//剪切上传后生成图片的规格（开启剪切才起使用）
            aspectRatio: 1 / 1//剪切区域的高宽比例（开启剪切才起使用）
        });
    }).on('click', '#selectHeadmaster', function () { // 选择班主任
        selectHeadmaster();
    }).on('click', 'i.fa-trash', function () { // 删除课程 班主任
        var tr = $(this).parents('tr');
        tr.remove();
        refreshPage();
    }).on('click', '#saveReturn', function () { // 发布，返回
        saveClasses(false);
    }).on('click', '#saveImport', function () { // 发布，导入学员
        saveClasses(true);
    }).on('click', '#saveCancel', function () { // 取消
        comeback();
    }).on("click","#remove-image",function(){
        removePageImg();
    }).on('blur',"input[name='studentLimitCount']",function(){//人数输入监听
        var value = $(this).val();
        if(!/\d+/.test(value)){
            $(this).val(0);
        }
    });

    /**
     * 自由班级
     * @return {boolean}
     */
    function isFreeClasses() {
        return $('input[name=classesType]:checked').val() == 2;
    }

    /**
     * 获得专业
     * @return {jQuery}
     */
    function getSubjectIds() {
        return $('input[name=subjectIds]').val() || '';
    }

    /**
     * 刷新页面显示效果
     */
    function refreshPage() {
        $('#classes-course div.noDataTipsBox').parents('tr').toggleClass('hide', !isEmptyCourse());
        $('#classes-headmaster div.noDataTipsBox').parents('tr').toggleClass('hide', !isEmptyHeadmaster());
        clearImage();
    }

    /**
     * 清空班级图标
     */
    function clearImage() {
        if (!isFreeClasses() && isEmptyCourse()) {
            $('#imageJson').val('');
            $('div.image').html('');
            $('#file-name').html('');
            $('#upload-time').html('');
            $('div.file-name').addClass('hide');
            $('i.fa-remove').parent().addClass('hide');
        }
    }

    function comeback() {
        window.location = baseloaction + '/admin/classes/classesList';
    }

    /**
     * 没有课程
     * @return {boolean}
     */
    function isEmptyCourse() {
        return $('#classes-course tr[data-course]').length == 0;
    }

    /**
     * 没有班主任
     * @return {boolean}
     */
    function isEmptyHeadmaster() {
        return $('#classes-headmaster tr[data-headmaster]').length == 0;
    }

    /**
     * 选择班主任
     */
    function selectHeadmaster() {
        selectTeacher('checkbox','','selectTeacherCallback','2');
    }

    /**
     * 保存班级
     * @param imports 导入学员
     */
    function saveClasses(imports) {
        var params = $('#classes-form').serializeJSON();
        params.courseId = getCourse();
        params.headmasterIds = getHeadmaster();
        params.status = 1;
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + '/admin/classes/saveClasses',
            data: params,
            dataType: 'json',
            type: 'post',
            contentType: 'application/json;charset=utf-8',
            success: function (response) {
                icModale(0, response.message);
                if(response.success){
                    if (imports) {
                        icModale(0, '去导入学员');
                        var obj = response.entity;
                        window.location = baseloaction + '/admin/classes/initUpdate?id='+obj.id+"&step="+2;
                    } else {
                        setTimeout(function () {
                            comeback();
                        }, 1500);
                    }
                }
            }
        });
    }

    function getCourse() {
        var course = $('#classes-course tr[data-course]');
        if (course.length > 0) {
            return course.map(function () {
                return this.dataset['course'];
            }).get().join(',');
        }
        return '';
    }

    function getHeadmaster() {
        var headmaster = $('#classes-headmaster tr[data-headmaster]');
        if (headmaster.length > 0) {
            return headmaster.map(function () {
                return this.dataset['headmaster'];
            }).get().join(',');
        }
        return '';
    }
});

/**
 * 班级名字为空
 * @return {boolean}
 */
function isEmptyCourseName() {
    return $('input[name=name]').val().length == 0;
}

/**
 * 选择课程回调
 * @param course 回调课程数据
 */
function selectCourseCallback(course) {
    course = convertToArray(course);
    $('#classes-course div.noDataTipsBox').parents('tr').toggleClass('hide', course.length > 0);
    course.forEach(function (v) {
        $('#classes-course tr[data-course]').remove();
        $('#classes-course').append('<tr data-course="' + v.id + '">' +
            '<td class="text-center">' + v.id + '</td>' +
            '<td class="text-center">' + v.courseName + '</td>' +
            '<td class="text-center"><a href="javascript:void(0)" data-original-title="删除" data-toggle="tooltip" class="c-master fs14"><i class="fa fa-trash"></i></a></td>' +
            '</tr>');
    });
    $('#classes-course a[data-toggle=tooltip]').tooltip();
    if (isEmptyCourseName()) {
        $('input[name=name]').val(course[course.length - 1].courseName)
    }
    var image = course[course.length - 1].image;
    uploadCallback(JSON.parse(decodeURIComponent(image)));
}

/**
 * 选择后台用户回调
 * @param user 回调后台用户数据
 */
function selectTeacherCallback(teacherList) {
    $('#classes-headmaster div.noDataTipsBox').parents('tr').toggleClass('hide', teacherList.length > 0);
    teacherList.forEach(function (v) {
        if ($('#classes-headmaster tr[data-headmaster=' + v.id + ']').length == 0) {
            $('#classes-headmaster').append('<tr data-headmaster="' + v.id + '">' +
                '<td class="text-center">' + v.id + '</td>' +
                '<td class="text-center">' + v.teacherName + '</td>' +
                '<td class="text-center"><a href="javascript:void(0)" data-original-title="删除" data-toggle="tooltip" class="c-master fs14"><i class="fa fa-trash"></i></a></td>' +
                '</tr>');
        }
    });
    $('#classes-headmaster a[data-toggle=tooltip]').tooltip();
}

function convertToArray(data) {
    if (Array.isArray(data)) return data;
    return [data];
}

// 图片上传回调
function uploadCallback(data) {
    $('#imageJson').val(encodeURIComponent(JSON.stringify(data)));
    $('div.image').html('<img class="img-responsive" src="' + data.pcUrlMap.small + '"/>');
    $('#file-name').html(data.fileName);
    $('#upload-time').html(data.createTime);
    $('div.file-name').removeClass('hide');
    $('i.fa-remove').parent().removeClass('hide');
}